import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {CustomValidators} from "ng2-validation";
import {AppService} from "../../system/services/app.service";
import {ResDataModel} from "../../system/models/res-data-model";

/**
 * Generated class for the MyDetailDemoPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-my-detail-demo',
  templateUrl: 'my-detail-demo.html',
})
export class MyDetailDemoPage {

  //当前选中项
  selectedItem: any;
  //表单数据
  public myForm:FormGroup;
  //自定义表单校验信息
  validation_messages = {
    'userName': '用户名不能为空',
    'money':'金额必须为大于0的数字'
  };
  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              public formBuilder:FormBuilder,
              private appService:AppService) {
    //从列表页面获取传入的数据
    this.selectedItem = this.navParams.get("item");
    //构建表单
    this.myForm=this.formBuilder.group({
      cId:[this.selectedItem.cId.value],
      userName:[this.selectedItem.userName.value,Validators.required],
      userSex:[this.selectedItem.userSex.value],
      money:[this.selectedItem.money.value,[CustomValidators.number,CustomValidators.min(0)]]
    });
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad MyDetailDemoPage');
  }

  /**
   * 表单保存提交
   * @param event
   */
  saveForm(){
    console.log(this.myForm.value);
    if(this.appService.validate(this.myForm,this.validation_messages)){
      this.saveData((data)=>{
        //返回上一页
        this.navCtrl.pop();
      })
    }
  }

  /**
   * 将数据保存到后端
   */
  saveData(successCallback?,failCallback?){
    let formModel = this.myForm.value;
    let postParam = {
      userInfo:{
        ryDm:formModel.cId,
        userName:formModel.userName,
        userSex:formModel.userSex,
        money:formModel.money,
      }
    }
    this.appService.httpPost('AppDemoUserCtrl_update',postParam,null,(res:ResDataModel)=>{
      var flag = res.datas[1].value;
      if(flag == "success"){
        //后台保存成功
        this.appService.smallToast("保存成功",'success');
        if(successCallback){
          successCallback(res.datas);
        }
      } else {
        this.appService.smallToast("保存失败","warning");
        if(failCallback){
          failCallback(res.datas);
        }
      }
    },true)
  }
}
